package service_sys

import (
	"encoding/json"
	"fmt"
	"strings"
	"wrblog-api-go/app/common/constants"
	"wrblog-api-go/app/dao/dao_sys"
	"wrblog-api-go/app/model/model_sys"
	"wrblog-api-go/pkg/redis"
	"wrblog-api-go/pkg/utils"
)

func GetDictDataPageList(sysDictData model_sys.SelectSysDictData) ([]model_sys.SysDictDataVo, int64, error) {
	return dao_sys.GetDictDataPageList(sysDictData)
}
func ApiDictDataByType(dictType string) (sysDictDatas []*model_sys.SysDictDataVo, err error) {
	val := redis.Get(fmt.Sprintf("%s%s", constants.SYS_DICT, dictType))
	if !utils.IsEmpty(val) {
		err = json.Unmarshal([]byte(val), &sysDictDatas)
	} else {
		sysDictDatas, err = dao_sys.ApiDictDataByType(dictType)
		if err != nil {
			return
		}
		data, _ := json.Marshal(sysDictDatas)
		err = redis.Set(fmt.Sprintf("%s%s", constants.SYS_DICT, dictType), string(data))
	}
	return
}

func GetDictDataById(dictCode int) (model_sys.SysDictDataVo, error) {
	return dao_sys.GetDictDataById(dictCode)
}

func AddDictData(sysDictData model_sys.SysDictDataPo) (int, error) {
	sysDictData.CreateTime = utils.NewTimeNow()
	return dao_sys.AddDictData(sysDictData)
}

func EditDictData(sysDictData model_sys.SysDictDataPo) (int64, error) {
	sysDictData.UpdateTime = utils.NewTimeNow()
	return dao_sys.EditDictData(sysDictData)
}

func RemoveDictData(dictCodes string, uk string) (int64, error) {
	return dao_sys.RemoveDictData(strings.Split(dictCodes, ","), uk)
}

func RemoveCacheAll() int {
	keys, _ := redis.ScanKeys(fmt.Sprintf("%s%s", constants.SYS_DICT, "*"))
	redis.Del(keys...)
	return len(keys)
}
